/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.job.biz.route.strategy;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import com.quanshi.scheduler.core.base.Ret;
import com.quanshi.scheduler.core.biz.model.TriggerParam;
import com.quanshi.scheduler.job.biz.route.ExecutorRouter;
import com.quanshi.scheduler.job.dal.entity.TriggerLog;

/**
 * 轮询
 * 
 * @author yanxiang.huang 2017-07-10 13:55:27
 */
public class ExecutorRouteRound extends ExecutorRouter
{
    private static ConcurrentHashMap<Long, Integer> routeCountEachJob = new ConcurrentHashMap<Long, Integer>();
    private static long CACHE_VALID_TIME = 0;

    @Override
    public String route( long jobId, ArrayList<String> addressList )
    {
        return addressList.get(count(jobId) % addressList.size());
    }

    @Override
    public Ret<String> routeRun( TriggerParam triggerParam, ArrayList<String> addressList, TriggerLog jobLog )
    {
        // address
        String address = route(triggerParam.getJobId(), addressList);
        jobLog.setExecutorAddress(address);

        // run executor
        Ret<String> runResult = runExecutor(triggerParam, address);
        runResult.setMsg("<br>----------------------<br>" + runResult.getMsg());

        return runResult;
    }
    
    private static int count( long jobId )
    {
        // cache clear
        if ( System.currentTimeMillis() > CACHE_VALID_TIME )
        {
            routeCountEachJob.clear();
            CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
        }

        // count++
        Integer count = routeCountEachJob.get( jobId );
        // 初始化时主动Random一次，缓解首次压力
        count = (count == null || count > 1000000) ? (new Random().nextInt( 100 )) : ++count;
        routeCountEachJob.put( jobId, count );
        return count;
    }

}
